package com.androidbook.garbagedemo1.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.androidbook.garbagedemo1.R;
import com.androidbook.garbagedemo1.api.Api;
import com.androidbook.garbagedemo1.api.ApiConfig;
import com.androidbook.garbagedemo1.api.TtitCallback;
import com.androidbook.garbagedemo1.entity.LoginResponse;
import com.androidbook.garbagedemo1.utils.StringUtils;
import com.google.gson.Gson;

import java.util.HashMap;

public class LoginActivity extends BaseActivity {
    private EditText etAccount;
    private EditText etPwd;
    private Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        etAccount=findViewById(R.id.et_account);
        etPwd=findViewById(R.id.et_pwd);
        btnLogin=findViewById(R.id.btn_login);
        //绑定点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取输入框输入的用户名及密码
                String account=etAccount.getText().toString().trim();//getText()获取输入框输入的文本，toString()文本类型转换，trim()去掉文本前后空格
                String pwd=etPwd.getText().toString().trim();
                login(account,pwd);
            }
        });
    }


    private void login(String account,String pwd){
        //调用StringUtils.isEmpty的方法判断账号密码是否为空
        if (StringUtils.isEmpty(account)){
            showToast("请输入账号");//（调用基类BaseActivity的封装方法）账号为空，弹出提示框
            return;
        }
        if (StringUtils.isEmpty(pwd)){
            showToast("请输入密码");
            return;
        }
        //使用OKHttp方法进行登录
        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put ( "mobile", account) ;
        params.put( "password" , pwd) ;
        Api.config(ApiConfig.LOGIN, params).postRequest(new TtitCallback() {
            @Override
            public void onSuccess(String res) {
                Log.e("onSuccess",res);
                Gson gson = new Gson();
                LoginResponse loginResponse = gson.fromJson( res,LoginResponse.class);
                if (loginResponse.getCode() == 0){
                    String token = loginResponse. getToken( );
                    saveStringToSp("token",token);
                    navigateTo(SearchActivity.class);

                    showToastSync( "登录成功");}
                else {
                    showToastSync("登录失败");
                }

            }

            @Override
            public void onFailure(Exception e) {

            }
        });

    }

}